package com.xuyiwei.mayi.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.mysql.jdbc.StringUtils;
import com.xuyiwei.mayi.alipay.config.AlipayConfig;
import com.xuyiwei.mayi.base.BaseApiService;
import com.xuyiwei.mayi.base.ResponseBase;
import com.xuyiwei.mayi.constants.Constants;
import com.xuyiwei.mayi.entity.PaymentInfo;
import com.xuyiwei.mayi.mapper.PaymentInfoDao;
import com.xuyiwei.mayi.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by xuyiwei on 2019/5/5.
 */
@RestController
public class PayServiceImpl extends BaseApiService implements PayService {
    @Autowired
    private PaymentInfoDao paymentInfoDao;

    @Override
    public ResponseBase createPayToken(@RequestBody PaymentInfo paymentInfo) {
        //先保存支付信息
        Integer count = paymentInfoDao.savePaymentType(paymentInfo);
        //然后把支付信息保存进redis里面  key为token   value为支付信息id  设置过期时间15分钟
        String payToken = TokenUtils.getPayToken();

        baseRedisService.setString(payToken,paymentInfo.getId()+"", (long) Constants.COOKIE_TOKEN_PAY_TIME);
        //然后返回token
        // 4.返回token
        JSONObject data = new JSONObject();
        data.put("payToken", payToken);
        return setResultSuccess(data);
    }

    @Override
    public ResponseBase findOrderByToken(@RequestParam("token") String token) {
        //根据token去redis里面读取支付
        if(StringUtils.isNullOrEmpty(token)){
            return setResultError("支付token不能为空");
        }
        String payIdStr = (String) baseRedisService.getString(token);
        //如果支付信息存在 则取出来
        if(StringUtils.isNullOrEmpty(payIdStr)){
            return setResultError("订单已经过期或者token无效");
        }

        PaymentInfo paymentInfo = paymentInfoDao.getPaymentInfo(new Long(payIdStr));
        if(paymentInfo==null){
            return setResultError("订单已经无效");
        }
        //然后对接支付宝
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = paymentInfo.getOrderId();
        // 付款金额，必填 企业金额
        String total_amount = paymentInfo.getPrice() + "";
        // 订单名称，必填
        String subject = "蚂蚁课堂充值会员";
        //商品描述，可空
        String body = "";


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        // 请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            JSONObject data = new JSONObject();
            data.put("payHtml", result);
            return setResultSuccess(data);
        } catch (Exception e) {
            return setResultError("支付异常");
        }
    }
}
